package com.test.practice.socket.tcp.returns;

import lombok.Cleanup;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @Description: =======================
 * @Author: Jovi
 * =======================
 * @Date: Created in 2023-02-10
 * =======================
 * @Version: 1.1.2.0
 */
public class TcpClientDemo {

    public static void main(String[] args) throws Exception {

        InetAddress address = InetAddress.getLocalHost();

        //1.先创建Socket对象，指明Server的IP+PORT
        @Cleanup Socket socket = new Socket(address, 9999);

        //2.获取输出流，用于输出到网络Socket中
        @Cleanup OutputStream os = socket.getOutputStream();

        //3.这里是从内存写出到 输出流中
        os.write("你好".getBytes());


        //关闭数据输出，告诉服务端已经传输完毕，否则服务端 read() 一直阻塞
        socket.shutdownOutput();



        byte[] datas = new byte[1024];

        @Cleanup InputStream is = socket.getInputStream();

        @Cleanup ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int len;
        while ((len = is.read(datas)) != -1) {
            baos.write(datas, 0, len);
        }

        System.out.println(baos);

    }
}
